const User = require('../models/User');
const { BadRequestError } = require('../errors');
const { StatusCodes } = require('http-status-codes');
const { genTokenToCookie } = require('../utils/jwt');

const login = async (req, res) => {
   const { phone, password } = req.body;

   if (!phone || !password) {
      throw new BadRequestError('手机号和密码不能为空');
   }

   const user = await User.findOne({ phone });
   if (!user) {
      throw new BadRequestError('该用户不存在');
   }

   // 对比密码
   const isPwdCorrect = await user.comparePwd(password);
   if (!isPwdCorrect) {
      throw new BadRequestError('密码错误');
   }

   genTokenToCookie(res, { userId: user._id, username: user.username, phone: user.phone, loginTime: new Date().toISOString() });
   res.status(StatusCodes.OK).json({
      msg: '登录成功',
      mainGroup: user.mainGroup,
      userId: user._id,
   });
};

const register = async (req, res) => {
   await User.create(req.body);
   res.status(StatusCodes.CREATED).json({
      msg: '创建成功',
   });
};

const logout = async (req, res) => {
   res.clearCookie('token');
   res.status(StatusCodes.OK).json({
      msg: '成功',
   });
};

module.exports = {
   login,
   logout,
   register,
};
